package org.orzeszek.transfer.comm;

import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.nio.SelectChannelConnector;

/**
 * {@link CommHelper}, uses an embedded {@link Server} to host services and
 * servlets on the user's machine.
 * 
 * @author Michael Gierasimiuk
 */
public class CommHelper
{
  private Server server;
  private Thread thread;

  /**
   * Creates a new {@link CommHelper} instance.
   */
  public CommHelper()
  {

  }

  /**
   * Initializes a {@link Server} with the given port.
   * 
   * @param port the port to run on the {@link Server}.
   */
  public void initialize( int port )
  {
    Connector connector = new SelectChannelConnector();
    connector.setPort( port );

    this.server = new Server();
    this.server.setConnectors( new Connector[] { connector } );
  }

  /**
   * Starts the thread.
   */
  public void start()
  {
    this.thread = new Thread( new ServerThread( this.server ) );
    this.thread.start();
  }

  /** Wraps a {@link Server} in a {@link Thread}. */
  private static class ServerThread implements Runnable
  {
    private Server server;

    /**
     * Creates a new {@link ServerThread} instance.
     * 
     * @param server the {@link Server} to run.
     */
    public ServerThread( Server server )
    {
      this.server = server;
    }

    @Override
    public void run()
    {
      try
      {
        this.server.start();
        this.server.join();
      }
      catch ( Exception e )
      {
        e.printStackTrace();
      }
    }
  }

  /** TODO: DEBUG ONLY. */
  public static void main( String[] args )
  {
    CommHelper manager = new CommHelper();
    manager.initialize( 8080 );
    manager.start();
  }
}
